﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;

namespace ESP.Data
{
    public class PredicateCommandParameters : CommandParameters
    {
        private bool _isOr;
        private IEnumerable<LambdaExpression> _expressions;
        private Dictionary<object, string> _tableMappings;

        public PredicateCommandParameters(string token, IEnumerable<LambdaExpression> expressions, Dictionary<object, string> tableMappings = null, bool isOr = false)
            : base(token)
        {
            _expressions = expressions;
            _isOr = isOr;
            _tableMappings = tableMappings;
        }

        protected internal override void Build()
        {
            SubParameters.Add(string.Empty, TranslatePredicate());
        }

        protected string TranslatePredicate()
        {
            StringBuilder builder = new StringBuilder();

            bool isFirst = true;
            foreach (var exp in _expressions)
            {
                if (!isFirst)
                {
                    builder.Append(_isOr ? " OR " : " AND ");
                }
                else
                {
                    isFirst = false;
                }
                TranslateExpression(builder, exp.Body, GetParameterTableNameMappings(exp.Parameters, _tableMappings));
            }

            return builder.ToString();
        }





    }
}
